﻿using CSharp.NetFramework.Entities;
using System.Data.Entity;

namespace CSharp.NetFramework.EF6
{
  public class EFContext : DbContext
  {
    const string SCHEMA_NAME = "dbo";

    public EFContext() : base("server=.;database=local_dev;uid=sa;pwd=123456;")
    {
      Database.Initialize(false);
    }

    public EFContext(string connstr) : base(connstr)
    {

    }

    // IDbSet<T> 没有 DbSet<T> 的批量操作方法
    public virtual DbSet<QualityQuestion> QualityQuestions { get; set; }

    public virtual DbSet<QualityQuestionDetail> QualityQuestionDetails { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      modelBuilder.Entity<QualityQuestion>()
        .HasKey(e => e.QualityQuestionGUID)
        .ToTable("cqm_QualityQuestion", SCHEMA_NAME)
        //Question端的导航熟悉Details 
        .HasMany(q => q.QuestionDetails)
        //Detail端的导航属性Question
        //.WithRequired(m => m.Question)
        .WithRequired()
        .HasForeignKey(d => d.QualityQuestionGUID)
        //启用级联删除
        .WillCascadeOnDelete();

      modelBuilder.Entity<QualityQuestionDetail>()
        .HasKey(e => e.QualityQuestionDetailGUID)
        //手动排除此属性
        .Ignore(m => m.EntityState)
        .ToTable("cqm_QualityQuestionDetail", SCHEMA_NAME);
    }

  }
}
